package com.hao.stack;

import java.util.Arrays;

/**
 * @Description: TODO
 * @author: a'hao
 * @date: 2021/4/24
 */
public class MyStackImpl<T> implements MyStack<T>{
    private final static Integer ARR_DEFAULT_SIZE = 100;
    private final static Integer DEFAULT_STACK_TOP =-1;
    /**
     * 存放栈数据的数组
     */
    private Object[] items;
    /**
     * 栈顶的index
     */
    private Integer stackTop;

    public MyStackImpl() {
        this(ARR_DEFAULT_SIZE);
    }

    public MyStackImpl(Integer stackSize) {
        this.items = new Object[stackSize];
        this.stackTop = DEFAULT_STACK_TOP;
    }

    public void push(T item) {
        boolean isOut = stackTop >= items.length;
        if (isOut){
            throw new RuntimeException();
        }else {
            stackTop++;
            items[stackTop] = item;
        }
    }

    public T pop() {
        boolean isOut = stackTop < 0;
        if (isOut){
            throw new RuntimeException();
        }else {
            T result = (T) items[stackTop];
            stackTop--;
            return result;
        }
    }

    public T get() {
        boolean isHas = stackTop > -1;
        if (isHas){
            return (T) items[stackTop];
        }
        return null;
    }

    public Integer size(){
        return stackTop+1;
    }

    @Override
    public String toString() {
        String result = "[";
        for (int i = 0; i < size(); i++) {
            result += items[i] + ",";
        }
        result = result.substring(0, result.length() - 1);
        result += "]";
        return result;
    }
}
